package com.mgm.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.mgm.result.IMessage;
import com.mgm.utils.AwsClient;


@Controller
@RequestMapping("/icon")
public class IconUploadController extends BaseController{
	
	private static Logger logger = LoggerFactory.getLogger(IconUploadController.class);
	
	/**
	 * 上传单个文件操作
	 * @param RequestParam 括号中的参数名file和表单的input节点的name属性值一致
	 * @return
	 */
	@RequestMapping(method=RequestMethod.POST)
	public ResponseEntity<IMessage> doUploadFile(@RequestParam("file") MultipartFile file){
		IMessage mes = IMessage.success();
		if(!file.isEmpty()){
			logger.info("【Icon上传】The file's contentType is {}, name is {}, size equal to {} and originalFilename is {}", file.getContentType(),
					file.getName(), file.getSize(), file.getOriginalFilename());
			try {
				if (file.getContentType().contains("image")) {
					File f = convertFile(file);
					String url = AwsClient.uploadToS3V2(f);  //file.getOriginalFilename()  --s3会报Md5错
					mes.setMsg(url);
				} else {
					mes.setCode(0);
					mes.setMsg("上传文件类型必须是图片格式");
				}
			} catch (Exception e) {
				logger.error("文件上传失败", e.getMessage());
				e.printStackTrace();
				return new ResponseEntity<IMessage>(IMessage.error("上传失败"), HttpStatus.OK);
				
			}
		}
		 
		return new ResponseEntity<IMessage>(mes, HttpStatus.OK);
	}

}
